package com.nearsoft.academy;

import java.io.*;
import java.util.*;

import android.content.ContentValues;
import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
import android.os.Environment;
import android.util.*;

public class LogDatabaseHandler extends SQLiteOpenHelper {
	 
	// Database Version
	private static final int DATABASE_VERSION = 2;
	// Database Name
	private static final String DATABASE_NAME = "log.db3";
	
	// Orientation table name
	private static final String ORIENTATION_TABLE_NAME = "orientationData";
	// Orientation columns names
	private static final String ORIEN_ID = "id";
	private static final String ORIEN_LOG_NAME = "log";
	private static final String ORIEN_DATE = "date";
	private static final String ORIEN_HEADING = "heading";
	private static final String ORIEN_PITCH = "pitch";
	private static final String ORIEN_ROLL = "roll";
	
	public LogDatabaseHandler(Context context){
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

    @Override
	public void onCreate(SQLiteDatabase db){
		// Orientation Create Table command string
		String ORIENTATION_TABLE_CREATE = "CREATE TABLE " + ORIENTATION_TABLE_NAME + " (" +
										  ORIEN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
										  ORIEN_LOG_NAME + " TEXT, " +
										  ORIEN_DATE + " DATETIME, " +
										  ORIEN_HEADING + " REAL, " +
										  ORIEN_PITCH + " REAL, " +
										  ORIEN_ROLL + " REAL)";
		db.execSQL(ORIENTATION_TABLE_CREATE);
	}
	
	// Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + ORIENTATION_TABLE_NAME);
        // Create tables again
        onCreate(db);
    }

    // Adding new List of OrientationData
    public void addOrientationDataList(String logName, List<OrientationData> orienDataList) {
        SQLiteDatabase db = this.getWritableDatabase();

        int i = 0;
        int size = orienDataList.size();
        //for (int i = 0; i < orienDataList.size(); i++){
        for(OrientationData orienData : orienDataList){
        	// Put Values for OrientationData
        	ContentValues values = new ContentValues();
        	
        	Log.i("DB", logName + " - Saving row " + String.valueOf(i + 1) + " of " + String.valueOf(size));
        	
        	values.put(ORIEN_LOG_NAME,  logName); // LogName
        	values.put(ORIEN_DATE, orienData.getDateEntered().getTime()); // Accelerometer Date Entered
        	values.put(ORIEN_HEADING, orienData.getAzimuthAngle()); // Heading value
        	values.put(ORIEN_PITCH, orienData.getPitchAngle()); // Pitch value
        	values.put(ORIEN_ROLL, orienData.getRollAngle()); // Roll value
     
        	// Inserting Row
        	db.insert(ORIENTATION_TABLE_NAME, null, values);
        	i++;
        }
        
        db.close(); // Closing database connection
    }

    public void deleteAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DROP TABLE IF EXISTS " + ORIENTATION_TABLE_NAME);
        onCreate(db);
    }
    
    // Get a list of OrientationData by LogName
    public List<OrientationData> getOrientationData(String logName){
    	SQLiteDatabase db = this.getReadableDatabase();

    	String selectQuery = "SELECT * FROM " + ORIENTATION_TABLE_NAME +
    						 " WHERE " + ORIEN_LOG_NAME + " = ?";

    	Cursor cursor = db.rawQuery(selectQuery, new String[] { logName });
    	List<OrientationData> orienDataList = new ArrayList<OrientationData>();

    	if (cursor.moveToFirst()){
	    	do{
	    		OrientationData element = new OrientationData(new Date(cursor.getLong(2)), cursor.getFloat(3), cursor.getFloat(4), cursor.getFloat(5));
	    		orienDataList.add(element);
	    	} while (cursor.moveToNext());
    	}
    	cursor.close();

    	return orienDataList;
    }

 // Get a list of LogNames
    public List<String> getLogNames(){
    	SQLiteDatabase db = this.getReadableDatabase();
    	String selectQuery = "SELECT DISTINCT " + ORIEN_LOG_NAME + " FROM " + ORIENTATION_TABLE_NAME;
    	
    	Cursor cursor = db.rawQuery(selectQuery, null);
    	List<String> LogNameList = new ArrayList<String>();
    	
    	if (cursor.moveToFirst()){
	    	do{
	    		String element = cursor.getString(0);
	    		LogNameList.add(element);
	    	} while (cursor.moveToNext());
    	}
    	cursor.close();
    	
    	return LogNameList;
    }
    
    public void saveToSD() {
    	List<String> logNames = this.getLogNames();
    	
    	StringBuilder output = new StringBuilder("");
    	String logName = "";
        File file   = null;
        File root   = Environment.getExternalStorageDirectory();

    	// Read Orientation Data
    	output = new StringBuilder("");
    	for (int i = 0; i < logNames.size(); i++){
    		int j = 0;
    		Log.i("DB", "Leyendo " + logNames.get(i));
    		List<OrientationData> orienList = this.getOrientationData(logNames.get(i));
    		//for (int j = 0; j < accList.size(); j++){
    		logName = logNames.get(i);
    		for (OrientationData orienData : orienList){
    			Log.i("DB", "Agregando a CSV - Orientation " + logName + " - " + String.valueOf(++j));
    			output.append("\"" ); output.append( logName); output.append("\"");
    			output.append(",\"" ); output.append(  orienData.getDateEntered().getTime() ); output.append( "\"");
    			output.append(",\"" ); output.append( orienData.getAzimuthAngle() ); output.append( "\"");
    			output.append(",\"" ); output.append( orienData.getPitchAngle() ); output.append( "\"");
    			output.append(",\"" ); output.append( orienData.getRollAngle() ); output.append( "\"");
    			output.append("\n");
    		}
    	}
    	
    	// Write Orientation Data to CSV
    	Log.i("DB", "Guardando OrientationData CSV...");
    	file   = null;
    	root   = Environment.getExternalStorageDirectory();
    	if (root.canWrite()){
    	    File dir    =   new File (root.getAbsolutePath() + "/PersonData");
		    dir.mkdirs();
		    file   =   new File(dir, "OrienLog.csv");
		    FileOutputStream out   =   null;
	     	try {
	        out = new FileOutputStream(file);
	        } catch (FileNotFoundException e) {
	        	Log.i("DB", e.getMessage());
	        }
	        try {
	            out.write(output.toString().getBytes());
	        } catch (IOException e) {
	        	Log.i("DB", e.getMessage());
	        }
	        try {
	            out.close();
	            Log.i("DB", "Guardado!!");
	        } catch (IOException e) {
	        	Log.i("DB", e.getMessage());
	        }
    	    
    	}
    	
    }
    	
    
}


